package com.listplayer;

import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PlayerList extends ListActivity {
	private FileArrayAdapter adapter;
	private File currentDir;
	private MediaPlayer player;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        
        String state = Environment.getExternalStorageState();
    	
    	if(!Environment.MEDIA_MOUNTED.equals(state))
    	{
    		return;
    	}
    	
    	player = new MediaPlayer();
    	
    	fillFileNames(new File( "/sdcard/"));
    	    	
    }
    
    private void fillFileNames( File file) {
    	AudioFilesFilter filter = new AudioFilesFilter();
    	File[] files = file.listFiles(filter);
    	this.setTitle(file.getName());
    	List<Option> dirs = new ArrayList<Option>();
    	List<Option> fls = new ArrayList<Option>();
    	
    	for( File f: files)
    	{
    		if(f.isDirectory())
    			dirs.add(new Option( f.getName(), "Directory", f.getAbsolutePath()));
    		else
    			fls.add( new Option( f.getName(), "Size: " + f.length(), f.getAbsolutePath()));    		
    	}
    	
    	Collections.sort(dirs);
    	Collections.sort(fls);
    	
    	dirs.addAll(fls);
    	if(!file.getName().equalsIgnoreCase("sdcard"))
    		dirs.add(0, new Option("..", "Parent Directory", file.getParent()));
    	
    	adapter = new FileArrayAdapter(PlayerList.this, R.layout.fileview, dirs);
    	this.setListAdapter(adapter);
	}

	@Override
    public void onListItemClick( ListView parent, View v, int position, long id) {
		super.onListItemClick(parent, v, position, id);
		Option o = adapter.getItem(position);
		if( o.getData().equalsIgnoreCase("directory") || o.getData().equalsIgnoreCase("parent directory"))
		{
			currentDir = new File(o.getPath());
			fillFileNames(currentDir);
		}
		else
			onFileClick(o.getPath());
    }

	private void onFileClick(String filename) 
	{
		if (player.isPlaying())
		{
			player.stop();
			player.reset();
		}
		
		//player = new MediaPlayer();
			
		try
		{
			player.setDataSource(filename);
			player.prepare();
			player.start();
		} catch (Exception e)
		{
			e.printStackTrace();			
		}
		
	}
}